package com.yuven.appframework.network;

import com.yuven.appframework.bean.BaseResponse;
import com.yuven.baselib.utils.GsonUtils;
import com.yuven.baselib.utils.Logger;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

public class RxHelper {

    public static <T> ObservableTransformer<BaseResponse<T>, T> transformResponse() {
        return new ObservableTransformer<BaseResponse<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<BaseResponse<T>> upstream) {
                return upstream.flatMap(new Function<BaseResponse<T>, Observable<T>>() {
                    @Override
                    public Observable<T> apply(BaseResponse<T> tBaseResponse) throws Exception {
                        Logger.i("RxHelper", "result from api : " + GsonUtils.toGson(tBaseResponse));
                        return createData(tBaseResponse);
                    }
                });
            }
        };
    }

    /*return tObservable -> tObservable.flatMap((Function<BaseResponse<T>, Observable<T>>) result -> {
        Logger.i("RxHelper","result from api : " + GsonUtils.toGson(result));
        return createData(result);
    });*/

    private static <T> Observable<T> createData(final BaseResponse<T> data) {
        return Observable.create(subscriber -> {
            if (ResultCode.HTTP_OK.equals(data.getCode())) {
                subscriber.onNext(data.getData());
            } else {
                //subscriber.onError(RetrofitException.unexpectedError(new Exception(data.getHead().getErrMsg())));
                if (ResultCode.CODE_TOKEN_FAILURE.equals(data.getCode())) {
                    //LoginStatusFailureUtils.INSTANCE.sendLoginTokenExpiredEvent();
                } else {
                    subscriber.onError(new ExceptionHandle.ServerException(data.getCode(), data.getMsg()));
                }
            }
            subscriber.onComplete();
        });
    }

    public static class HttpErrorHandleFunc<T> implements Function<Throwable, Observable<T>> {
        @Override
        public Observable<T> apply(Throwable throwable) throws Exception {
            return Observable.error(ExceptionHandle.handleException(throwable));
        }
    }

}
